<template>
  <div>
    <el-menu
      :default-active="active"
      class="index-side-menu"
      active-text-color="red"
    >
      <a v-for="(item,i) in menuList"
         :key="i"
         :index="item.index"
         @click="goAnchor(item.link)">
        <el-menu-item  :index="item.index">
          <i v-bind:class="item.icon"></i>
          <span slot="title">{{item.name}}</span>
        </el-menu-item>
      </a>
    </el-menu>
  </div>
</template>

<script>
export default {
  name: "SideMenu",
  data(){
    return{
      active:"1",
      menuList:[
        {name:'关于我们',link:'about-us',index:'1',icon:'el-icon-s-home'},
        {name:'新的论文',link:'new-paper',index:'2',icon:'el-icon-paperclip'},
        {name:'我的笔记',link:'my-note',index:'3',icon:'el-icon-reading'},
        {name:'我收到的评论',link:'my-comment',index:'4',icon:'el-icon-chat-round'}
      ]
    }
  },
  //添加元素滚动的监听事件
  mounted() {
    window.addEventListener('scroll',this.onScroll)
  },

  //在页面销毁的时候移除监听器
  destroyed() {
    window.removeEventListener('scroll',this.onScroll)
  },

  methods:{
    goAnchor(id){
      var anchor =document.getElementById(id)
      anchor.scrollIntoView()
    },
    onScroll(){
      const navContents = document.querySelectorAll('.el-collapse-item')
      const offsetTopArr = []
      navContents.forEach(item =>{
        offsetTopArr.push(item.offsetTop)
      })
      const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
      let navIndex = 1
      for(let n= 0; n<=offsetTopArr.length;n++)
      {
        if(scrollTop>=offsetTopArr[n]) {
          navIndex=n+1
        }
      }
      this.active=navIndex+''
    }
  }
}
</script>

<style scoped>
a {
  text-decoration: none;
  color: inherit;
}

div{
  caret-color: transparent;
}

.index-side-menu{
  width: 170px;
  position: fixed;
}
</style>
